using UnityEngine;
using UnityEngine.UIElements;
using System.IO;
using UnityEngine.Networking;
using System.Collections;

public class FileUploadUI : MonoBehaviour
{
    private TextField serverAddressField;
    private Button selectFileButton;
    private Button uploadButton;
    private Label statusLabel;
    private string selectedFilePath;

    private void OnEnable()
    {
        var root = GetComponent<UIDocument>().rootVisualElement;

        serverAddressField = root.Q<TextField>("ServerAddressField");
        selectFileButton = root.Q<Button>("SelectFileButton");
        uploadButton = root.Q<Button>("UploadButton");
        statusLabel = root.Q<Label>("StatusLabel");

        selectFileButton.clicked += SelectFile;
        uploadButton.clicked += UploadFile;
    }

    private void SelectFile()
    {
        selectedFilePath = UnityEditor.EditorUtility.OpenFilePanel("选择小说文件", "", "txt");
        if (!string.IsNullOrEmpty(selectedFilePath))
        {
            statusLabel.text = "已选择文件: " + Path.GetFileName(selectedFilePath);
        }
    }

    private void UploadFile()
    {
        if (string.IsNullOrEmpty(selectedFilePath))
        {
            ShowError("请先选择一个文件。");
            return;
        }

        string serverAddress = serverAddressField.value;
        if (string.IsNullOrEmpty(serverAddress))
        {
            ShowError("请输入服务器地址。");
            return;
        }

        StartCoroutine(UploadFileCoroutine(serverAddress, selectedFilePath));
    }

    private IEnumerator UploadFileCoroutine(string serverAddress, string filePath)
    {
        byte[] fileData = File.ReadAllBytes(filePath);
        WWWForm form = new WWWForm();
        form.AddBinaryData("file", fileData, Path.GetFileName(filePath));

        using (UnityWebRequest www = UnityWebRequest.Post(serverAddress, form))
        {
            yield return www.SendWebRequest();

            if (www.result != UnityWebRequest.Result.Success)
            {
                ShowError("上传失败: " + www.error);
            }
            else
            {
                ShowSuccess("上传成功！");
                string sqliteFilePath = www.downloadHandler.text;
                // 通知 DataPreviewUI 加载数据
                DataPreviewUI.Instance.LoadDataFromSQLite(sqliteFilePath);
            }
        }
    }

    private void ShowError(string message)
    {
        statusLabel.text = "错误: " + message;
        statusLabel.style.color = Color.red;
    }

    private void ShowSuccess(string message)
    {
        statusLabel.text = message;
        statusLabel.style.color = Color.green;
    }
}